<?php

namespace App\Logic;

use App\Models\AdminMenu;
use App\Models\AdminNode;
use App\Models\AdminUser as ModelsAdminUser;
use Illuminate\Support\Facades\Cache;

class AdminUser
{

    const LOGIN_KEY = 'admin:login:';

    function __construct()
    {
        $this -> model = new ModelsAdminUser;
        $this -> modelMenu = new AdminMenu;
        $this -> modelNode = new AdminNode;
    }

    /**
     * 登录
     */
    public function login($account, $password)
    {
        $user = $this -> model -> where(['account' => $account]) -> first();
        if (!$user) return false;
        if (!password_verify($password, $user['password'])) return false;

        $token = md5(mt_rand(1000, 9999).time().'xt');  // 生成token
        Cache::put(self::LOGIN_KEY.$token, $user['id'], 3600*24*3);  // token绑定uid
        $data['token'] = $token;
        $data['user_info'] = $this -> model -> userInfo($user['id']);
        return $data;
    }

    /**
     * 登出
     */
    public function logout($token)
    {
        Cache::forget(self::LOGIN_KEY.$token);
    }

    /**
     * 获取api节点列表
     */
    public function apiNodeList($menuIds)
    {
        $menuList = $this -> modelMenu -> select('node_ids') -> whereIn('id', explode(',', $menuIds)) -> get() -> toArray();
        if (!$menuList) return false;
        $nodeIds = implode(',', array_column($menuList, 'node_ids'));
        $nodeList = $this -> modelNode -> select('path') -> whereIn('id', explode(',', $nodeIds)) -> get() -> toArray();
        if (!$nodeList) return false;
        return array_column($nodeList, 'path');
    }

}